import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
// import { useSnapshot } from 'valtio'
// import store from '@/store';
import style from './index.module.less';
import { getData, editData, addData, delData } from '@/api';
import { Table, Button, Modal, Form, Input, message, TableProps } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { uuid } from '@/utils';

type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];

interface TableRowData {
  id: string;
  name: string;
  quotas: number;
  lenders: number;
  cycle: number;
  score: number;
  returned: number;
}

interface TableData {
  id: string;
  title: string;
  list: TableRowData[];
}

interface TableViewProps {
  tableDatas: TableData;
  callBack: () => void; // 如果 callBack 是可选的，可以加上 ?
}

const TableView: React.FC<TableViewProps> = ({tableDatas, callBack}) => {
  // debugger
  // 表头
  const columns = [
    {
      title: '公司',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '批额',
      dataIndex: 'quotas',
      key: 'quotas',
    },
    {
      title: '放款',
      dataIndex: 'lenders',
      key: 'lenders',
    },
    {
      title: '周期',
      dataIndex: 'cycle',
      key: 'cycle',
    },
    {
      title: '评分',
      dataIndex: 'score',
      key: 'score',
    },
    {
      title: '状态',
      dataIndex: 'returned',
      key: 'returned',
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'x',
      render: (record: TableRowData) => {
        return (
          <>
            <a onClick={() => editFn(record)}>编辑</a>
            &nbsp;&nbsp;&nbsp;
            <a style={{ color: '#f34a4a' }} onClick={() => delFn(record)}>删除</a>
          </>
        )
      },
    },
  ];

  const [selectedRows, setSelectedRows] = useState<TableRowData[]>([]);
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  // 标题
  const [modalTitle, setModalTitle] = useState<string>('添加');
  // 列表数据
  // const [tableDatas, setTableDatas] = useState<TableData[]>(tableDatas);
  // 编辑弹窗
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  // 单条数据
  const [itemTable, setItemTable] = useState<TableRowData>({
  } as TableRowData);
  // 数据id
  const [id, setId] = useState<any>(0);

  const { confirm } = Modal;

  const onSelectChange = (newSelectedRowKeys: React.Key[], selectedRows: TableRowData[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys, selectedRows);
    setSelectedRows(selectedRows);
  };

  const rowSelection: TableRowSelection<TableRowData> = {
    onChange: onSelectChange,
  };

  // const getDataFn = () => {
  //   // 获取风控数据
  //   getData().then(res => {
  //     console.log(res);
  //     if (res.data.code == 200) {
  //       setTableDatas(res.data.data)
  //     } else {
  //       setTableDatas([])
  //       console.log("数据获取失败！")
  //     }
  //   })
  // }
  const validateMessages = {
    required: '${label} 不能为空!',
  };

  // 添加
  const addList = () => {
    let addObj = {
      id: '',
      name: '',
      quotas: 0,
      lenders: 0,
      cycle: 0,
      score: 0,
      returned: 0
    }
    setItemTable(addObj);
    form.setFieldsValue(addObj)
    // 修改弹窗title
    setModalTitle('添加');
    // 打开弹窗
    setIsModalOpen(true);
  };
  // 编辑
  const editFn = (record: TableRowData) => {
    form.resetFields();
    console.log(record);
    // 数据id
    setId(record.id)
    // 单条数据
    setItemTable(record);
    // 单条数据（用于回显）
    form.setFieldsValue(record)
    // 修改弹窗title
    setModalTitle('编辑');
    // 打开弹窗
    setIsModalOpen(true);
  };

  // 取消编辑 
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 提交编辑
  const onFinish = (values: any) => {
    console.log('Success:', values);
    setIsModalOpen(false);
    if (modalTitle == '添加') {
      let obj = { ...values, id: uuid(8, 16), titleId: tableDatas?.id }
      addData(obj).then(res => {
        if (res.data.code == 200) {
          messageApi.open({
            type: 'success',
            content: '添加成功',
          });
          callBack();
        } else {
          messageApi.open({
            type: 'error',
            content: '添加失败！',
          });
        }
      })
    } else {
      editData({ ...values, id, titleId: tableDatas?.id }).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          messageApi.open({
            type: 'success',
            content: '编辑成功',
          });
          callBack();
        } else {
          messageApi.open({
            type: 'error',
            content: '编辑失败！',
          });
        }
      })
    }
  };

  // 批量删除
  const delMore = () => {
    let idArr: string[] = []
    // 批量删除
    if (selectedRows.length) {
      selectedRows.map(item => {
        idArr.push(item.id)
      })
      del(idArr)
    }
  };
  // 删除
  const delFn = (item: TableRowData) => {
    let idArr: string[] = []
    idArr = [item.id]
    del(idArr)
  }
  // 删除方法
  const del = (idArr: string[]) => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      cancelText: '取消',
      content: <div>确认删除？<span style={{ color: '#f00' }}>(删除不可恢复)</span></div>,
      onOk() {
        delData({ ids: idArr, titleId: tableDatas?.id }).then(res => {
          if (res.data.code == 200) {
            messageApi.open({
              type: 'success',
              content: '删除成功',
            });
            callBack();
          } else {
            messageApi.open({
              type: 'error',
              content: '删除失败！',
            });
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  };
  // 获取数据
  useEffect(() => {
    callBack();
  }, []);
  return (
    <>
      {contextHolder}
      <div className={style['content-header']}>
        {
          tableDatas.title ? (
            <div className={style['header-title']}>{tableDatas.title}（共{tableDatas.list.length}条）</div>
          ) : (
            ''
          )
        }
        <div>
          <Button type="primary" danger style={{marginRight: 10}} onClick={() => delMore()}>
            批量删除
          </Button>
          <Button type="primary" onClick={() => addList()}>
            添加
          </Button>
        </div>
      </div>
      {tableDatas.list ? (
        <Table
          rowSelection={rowSelection}
          dataSource={tableDatas.list}
          columns={columns}
          rowKey={record => record.name}
          tableLayout="fixed"
          scroll={{ x: 'max-content', y: 55 * 11 }}
        />
      ) : (
        <p>暂无数据</p>
      )}
      {/* 编辑 */}
      <Modal title={modalTitle} open={isModalOpen} onCancel={handleCancel} footer={null}>
        <Form
          form={form}
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          wrapperCol={{ flex: 1 }}
          colon={false}
          style={{ maxWidth: 600 }}
          size="large"
          initialValues={itemTable}
          validateMessages={validateMessages}
          onFinish={onFinish}
        >
          <Form.Item label="企业" name="name" rules={[{ required: true }]}>
            <Input />
          </Form.Item>

          <Form.Item label="批额" name="quotas" rules={[{ required: true }]}>
            <Input />
          </Form.Item>

          <Form.Item label="放款" name="lenders" rules={[{ required: true }]}>
            <Input />
          </Form.Item>

          <Form.Item label="周期" name="cycle" rules={[{ required: true }]}>
            <Input />
          </Form.Item>

          <Form.Item label="评分" name="score" rules={[{ required: true }]}>
            <Input />
          </Form.Item>

          <Form.Item label="状态" name="returned" rules={[{ required: true }]}>
            <Input />
          </Form.Item>

          <Form.Item label=" ">
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default TableView;